package com.dhp.utils;

import com.dhp.Exception.exception;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.dhp.Constant.UserConstant.*;

@Slf4j
public class CookieUtil {
    /**
     * 创建cookie
     * @param token
     * @param response
     */
    public static void setLoginToken(String token , HttpServletResponse response){
        //初始化cookie 访问域名，访问请求路径，过期时间
        Cookie cookie = new Cookie(COOKIE_NAME , token);
        cookie.setMaxAge(COOKIE_EXPIRE);
        //cookie.setDomain(".localhost");
        cookie.setHttpOnly(true);
        cookie.setPath("/");

        //返回cookie到浏览器
        log.info("当前cookie为{} + {}"  , cookie.getName() , cookie.getValue());
        response.addCookie(cookie);
    }

    /**
     * 删除cookie通过覆盖
     * @param request
     * @param response
     */
    public static void removeLoginToken(HttpServletRequest request , HttpServletResponse response){
        //获取Cookie
        Cookie[] cookies = request.getCookies();
        if (cookies == null){
            log.info("cookie为空");
            return;
        }

        boolean loginStatus = false;
        //遍历cookies数组，寻找cookieName匹配的
        for (Cookie cookie : cookies) {
            if (COOKIE_NAME.equals(cookie.getName())){
                //匹配成功删除该cookie
                cookie.setMaxAge(COOKIE_DELETE);
                response.addCookie(cookie);
                loginStatus = true;
                break;
            }
        }
        //并未找到与之匹配的cookie
        if (!loginStatus){
            throw new exception("无法注销,用户未登录" , 40006 , "用户未登录");
        }
    }

    /**
     * 读取cookie中的内容
     * @param request
     * @return
     */
    public static String readLoginToken(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if (cookies == null){
            return null;
        }

        //遍历cookies数组，寻找cookieName匹配的
        for (Cookie cookie : cookies) {
            if (COOKIE_NAME.equals(cookie.getName())){
                return cookie.getValue();
            }
        }
        return null;
    }
}
